package com.tanhua.dubbo.api;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //发布评论，并获取评论数量
    public Integer save(Comment comment) {
        //1、查询动态
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
        //2、向comment对象设置被评论人属性
        if (movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    //保存点赞
    public Integer saveVideo(Comment comment) {
        //1、查询动态
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        //2、向comment对象设置被评论人属性
        if(video != null) {
            comment.setPublishUserId(video.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video modify = mongoTemplate.findAndModify(query, update, options, Video.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType() );
    }

    //分页查询
    public List<Comment> findComments(String movementId, CommentType commentType, Integer page, Integer pagesize) {
        //1、构造查询条件
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType")
                .is(commentType.getType()))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2、查询并返回
        return mongoTemplate.find(query, Comment.class);
    }

    //判断comment数据是否存在
    public Boolean hasComment(String movementId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query, Comment.class); //判断数据是否存在
    }

    //删除
    public Integer delete(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);
        //2、修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    //发布评论存储或者更新
    @Override
    public Integer saveCommentVideo(Comment comment) {
        //1、查询视频动态
        Comment commentVideo = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        Video video = mongoTemplate.findById(commentVideo.getPublishId(), Video.class);
        //2、向comment对象设置被评论人属性
        if (video != null) {
            comment.setPublishUserId(video.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(video.getId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Video modify = mongoTemplate.findAndModify(query, update, options, Video.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    //删除视频评论点赞
    @Override
    public Integer delCommentVideo(Comment comment) {
        //1、获取评论数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("id").is(comment.getId());
        Query query = Query.query(criteria);
        Comment updateComment = mongoTemplate.findOne(query, Comment.class);
        //2、修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(updateComment.getId()));
        Update update = new Update();
        update.inc("likeCount", -1);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(movementQuery, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return modify.getLikeCount();
    }

    //更新点赞
    @Override
    public Integer updateVideo(Comment comment) {
        //1、查询评论
        Comment commentVideo = mongoTemplate.findById(comment.getId(), Comment.class);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(commentVideo.getId()));
        Update update = new Update();
        update.inc("likeCount", 1);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(query, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return modify.getLikeCount();
    }

    /**
     * 评论点赞数
     *
     * @param comment
     * @return
     */
    public Integer plsave(Comment comment) {
        //1、查询动态
        Comment comment1 = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        //2、向comment对象设置被评论人属性
        if (comment1 != null) {
            comment.setPublishUserId(comment1.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(query, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    //删除
    public Integer deleteVideo(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query,Comment.class);
        //2、修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",-1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video modify = mongoTemplate.findAndModify(movementQuery, update, options, Video.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType() );
    }

    /**
     * 点赞列表-评论列表
     * @param publishUserId
     * @return
     */

    public List<Comment> findByPublishUserId(Long publishUserId,CommentType commentType) {
        //构建查询条件
        if (commentType.getType() == 1) {
            Query query = Query.query(Criteria.where("publishUserId").is(publishUserId)
                    .and("commentType").is(commentType.getType()));
            List<Comment> list = mongoTemplate.find(query, Comment.class);
            return list;
        }else if(commentType.getType() == 2){
            Query query = Query.query(Criteria.where("publishUserId").is(publishUserId)
                    .and("commentType").is(commentType.getType()));
            List<Comment> list = mongoTemplate.find(query, Comment.class);
            return list;
        }
        return new ArrayList<>();
    }

    /**
     * 取消评论点赞
     *
     * @param comment
     * @return
     */
    public Integer pldelete(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);
        //2、修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(movementQuery, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

//    //是否点赞
//    @Override
//    public Boolean hasCommentVideo(String commentId, Long userId, CommentType commentType) {
//        //获取对应的评论
//        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
//        String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + userId;
//        //判断是否存在
//
//        Criteria criteria = Criteria.where("userId").is(userId)
//                .and("publishId").is(new ObjectId(commentId))
//                .and("commentType").is(commentType.getType());
//        Query query = Query.query(criteria);
//        Comment comment = mongoTemplate.findOne(query, Comment.class);
//
//        return mongoTemplate.exists(query,Comment.class); //判断数据是否存在
//    }
}
